package com.fc.primary.algorithm;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: fc-java->Bean2Map
 * @description: 对象跟map互转
 * @author: G_Y
 * @create: 2019-09-04 16:46
 **/
public class Bean2Map {
    /**
     * 转换bean为map
     *
     * @param source 要转换的bean
     * @param <T>    bean类型
     * @return 转换结果
     */
    public static <T> Map<String, Object> bean2Map(T source) throws IllegalAccessException {
        Map<String, Object> result = new HashMap<>();

        Class<?> sourceClass = source.getClass();
        //拿到所有的字段,不包括继承的字段
        Field[] sourceFiled = sourceClass.getDeclaredFields();
        for (Field field : sourceFiled) {
            field.setAccessible(true);//设置可访问,不然拿不到private
            result.put(field.getName(), field.get(source));
        }
        return result;
    }

    /**
     * map转bean
     *
     * @param source   map属性
     * @param instance 要转换成的备案
     * @return 该bean
     */
    public static <T> T map2Bean(Map<String, Object> source, Class<T> instance) {
        try {
            T object = instance.newInstance();
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                field.set(object, source.get(field.getName()));
            }
            return object;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Bean bean = new Bean();
        bean.setAge(50);
        bean.setName("gaoyue");
        Map<String, Object> map = null;
        try {
            map = bean2Map(bean);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        System.out.println(map);

        bean = map2Bean(map, Bean.class);
        System.out.println(bean);

    }
}

class Bean {

    String name;
    int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Bean{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
